<template>
    <div class="container">
        <Breadcrumb :items="['menu.report', 'menu.report.order']" />
        <a-card class="general-card" :title="$t('order.list')">
            <a-row>
                <a-col :flex="1">
                    <a-form
                        :model="formModel"
                        :label-col-props="{ span: 6 }"
                        :wrapper-col-props="{ span: 18 }"
                        label-align="left"
                    >
                        <a-row :gutter="24">
                            <a-col :span="6">
                                <a-form-item
                                    field="fuelCode"
                                    :label="$t('order.fuelCode')"
                                >
                                    <a-select
                                        v-model="formModel.fuelCode"
                                        allow-clear
                                        style="width: 200px"
                                        :placeholder="
                                            $t(
                                                'order.form.fuelCode.placeholder'
                                            )
                                        "
                                    >
                                        <a-option
                                            v-for="item in fuelList"
                                            :key="item.fuelId"
                                            :value="item.fuelCode"
                                            :label="item.fuelName"
                                        ></a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="companyId"
                                    :label="
                                        $t('order.form.cheduiId.placeholder')
                                    "
                                >
                                    <a-select
                                        v-model="formModel.companyId"
                                        allow-clear
                                        allow-search
                                        style="width: 240px"
                                        :placeholder="
                                            $t(
                                                'order.form.cheduiId.placeholder'
                                            )
                                        "
                                    >
                                        <a-option
                                            v-for="item in cheduiList"
                                            :key="item.companyId"
                                            :value="item.companyId"
                                            :label="item.companyName"
                                        ></a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="10">
                                <a-form-item
                                    field="time"
                                    :label="$t('order.createdTime')"
                                >
                                    <a-range-picker
                                        v-model="formModel.time"
                                        style="width: 100%"
                                        show-time
                                        :time-picker-props="{
                                            defaultValue: [
                                                '00:00:00',
                                                '08:00:00',
                                            ],
                                        }"
                                        format="YYYY-MM-DD HH:mm:ss"
                                        :shortcuts="[
                                            {
                                                label: '最近1天',
                                                value: () => [
                                                    dayjs(),
                                                    dayjs().add(-1, 'day'),
                                                ],
                                            },
                                            {
                                                label: '最近7天',
                                                value: () => [
                                                    dayjs(),
                                                    dayjs().add(-1, 'week'),
                                                ],
                                            },
                                            {
                                                label: '最近30天',
                                                value: () => [
                                                    dayjs(),
                                                    dayjs().add(-1, 'month'),
                                                ],
                                            },
                                            {
                                                label: '最近365天',
                                                value: () => [
                                                    dayjs(),
                                                    dayjs().add(-1, 'year'),
                                                ],
                                            },
                                        ]"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="status"
                                    :label="$t('order.status')"
                                >
                                    <a-select
                                        v-model="formModel.status"
                                        style="width: 200px"
                                        :options="contentTypeOptions"
                                        :placeholder="
                                            $t('search.form.selectDefault')
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="customerId"
                                    :label="
                                        $t('order.form.customerId.placeholder')
                                    "
                                >
                                    <a-select
                                        v-model="formModel.customerId"
                                        :style="{ width: '180px' }"
                                        placeholder="选择会员"
                                        allow-search
                                        allow-clear
                                    >
                                        <template
                                            v-for="item in vipSelects"
                                            :key="item.customerId"
                                        >
                                            <a-option
                                                :value="item.customerId"
                                                >{{
                                                    item.customerName
                                                }}</a-option
                                            >
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <!-- <a-switch
                                v-model="isAllStation"
                                @change="changeStationAll()"
                            >
                                <template #checked> 全部站点ON </template>
                                <template #unchecked> 全部站点OFF </template>
                            </a-switch> -->
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider style="height: 42px" direction="vertical" />
                <a-col :flex="'86px'" style="text-align: right">
                    <a-space :size="18">
                        <a-button type="primary" @click="search(1)">
                            <template #icon>
                                <icon-search />
                            </template>
                            {{ $t('search.form.search') }}
                        </a-button>
                        <a-button type="primary" @click="exportExcel()">
                            <template #icon>
                                <icon-download />
                            </template>
                            {{ $t('search.form.export') }}
                        </a-button>
                        <a-button @click="reset">
                            <template #icon>
                                <icon-refresh />
                            </template>
                            {{ $t('search.form.reset') }}
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
            <a-divider style="margin-top: 0" />
            <a-row style="margin-bottom: 16px">
                <a-col
                    :span="12"
                    style="
                        display: flex;
                        align-items: center;
                        justify-content: end;
                    "
                >
                    <a-tooltip :content="$t('refresh')">
                        <div class="action-icon" @click="() => search()">
                            <icon-refresh size="18" />
                        </div>
                    </a-tooltip>
                    <a-tooltip :content="$t('table.column.setting')">
                        <a-popover
                            trigger="click"
                            position="bl"
                            @popup-visible-change="popupVisibleChange"
                        >
                            <div class="action-icon"
                                ><icon-settings size="18"
                            /></div>
                            <template #content>
                                <div id="tableSetting">
                                    <div
                                        v-for="(item, index) in showColumns"
                                        :key="item.dataIndex"
                                        class="setting"
                                    >
                                        <div
                                            style="
                                                margin-right: 4px;
                                                cursor: move;
                                            "
                                        >
                                            <icon-drag-arrow />
                                        </div>
                                        <div>
                                            <a-checkbox
                                                v-model="item.checked"
                                                @change="
                                                    handleChange(
                                                        $event,
                                                        item as TableColumnData,
                                                        index
                                                    )
                                                "
                                            >
                                            </a-checkbox>
                                        </div>
                                        <div class="title">
                                            {{
                                                item.title === '#'
                                                    ? '序列号'
                                                    : item.title
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </a-popover>
                    </a-tooltip>
                </a-col>
            </a-row>
            <a-table
                row-key="id"
                :loading="loading"
                :pagination="pagination"
                :columns="(cloneColumns as TableColumnData[])"
                :data="renderData"
                :bordered="false"
                :size="size"
                :scroll="scroll"
                :scrollbar="scrollbar"
                @page-change="onPageChange"
            >
                <template #status="{ record }">
                    <div>
                        <div v-if="record.status == 1">
                            <span class="circle pass"></span>
                            <span>{{ $t('enable') }}</span>
                        </div>
                        <div v-else>
                            <span class="circle pass"></span>
                            <span>{{ $t('disable') }}</span>
                        </div>
                    </div>
                </template>
            </a-table>
        </a-card>
    </div>
</template>

<script lang="ts" setup>
    import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
    // import { useRouter } from 'vue-router';
    import moment from 'moment';
    import dayjs from 'dayjs';
    import qee from 'qf-export-excel';
    import { useI18n } from 'vue-i18n';
    import useLoading from '@/hooks/loading';
    import { Pagination } from '@/types/global';
    import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
    import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
    import cloneDeep from 'lodash/cloneDeep';
    import pick from 'lodash/pick';
    import Sortable from 'sortablejs';
    import { getList, del, getFuelList, getCheduiList } from './service';

    type SizeProps = 'mini' | 'small' | 'medium' | 'large';
    type Column = TableColumnData & { checked?: true };

    const generateFormModel = () => {
        return {
            fuelCode: '',
            companyId: '',
            customerId: '',
            time: [
                moment(new Date()).format('YYYY-MM-DD 00:00:00'),
                moment(new Date()).format('YYYY-MM-DD 23:59:59'),
            ],
            status: '',
        };
    };
    const { loading, setLoading } = useLoading(true);
    const { t } = useI18n();
    const contentTypeOptions = computed<SelectOptionData[]>(() => [
        {
            label: t('order.wzf'),
            value: '1',
        },
        {
            label: t('order.yzf'),
            value: '2',
        },
    ]);
    // const router = useRouter();
    const renderData = ref<any[]>([]);
    const renderExcelData = ref<any[]>([]);
    const fuelList = ref<any[]>([]);
    const cheduiList = ref<any[]>([]);
    const vipSelects = ref<any[]>([]);
    const formModel = ref(generateFormModel());

    const cloneColumns = ref<Column[]>([]);
    const showColumns = ref<Column[]>([]);

    const size = ref<SizeProps>('medium');

    const isAllStation = ref(true);
    const scrollbar = ref(true);
    const scroll = {
        x: 2000,
        y: 600,
    };

    const pagination = reactive({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const getFuelListDtat = async () => {
        const data = await getFuelList();
        // formModel.value.fuelCode = data?.result?.[0]?.fuelId;
        fuelList.value = data?.result || [];
    };
    getFuelListDtat();
    const getCheduiListDtat = async () => {
        const data = await getCheduiList();
        cheduiList.value = data?.result.company || [];
        vipSelects.value = data?.result.customer || [];
    };
    getCheduiListDtat();

    const columns = computed<TableColumnData[]>(() => [
        {
            title: t('order.consumeId'),
            dataIndex: 'consumeId',
            width: 90,
        },
        {
            title: t('order.stationName'),
            dataIndex: 'stationName',
            width: 120,
        },

        {
            title: t('order.fuelName'),
            dataIndex: 'fuelName',
            width: 90,
        },
        {
            title: t('order.nzn'),
            dataIndex: 'nzn',
            width: 70,
        },
        {
            title: t('order.price'),
            dataIndex: 'price',
            width: 90,
        },
        {
            title: t('order.volume'),
            dataIndex: 'volume',
            width: 120,
        },
        {
            title: t('order.amount'),
            dataIndex: 'amount',
            width: 120,
        },
        {
            title: t('order.payAmount'),
            dataIndex: 'payAmount',
            width: 80,
        },

        {
            title: t('order.status'),
            dataIndex: 'status',
            width: 80,
            render({ record }) {
                return (
                    {
                        1: t('order.wzf'),
                        2: t('order.yzf'),
                    } as any
                )[record.status];
            },
        },
        {
            title: t('order.tradeTime'),
            dataIndex: 'tradeTime',
            width: 130,
        },
        {
            title: t('order.customerName'),
            dataIndex: 'customerName',
            width: 90,
        },
        {
            title: t('order.companyName'),
            dataIndex: 'companyName',
            width: 140,
        },
        {
            title: t('order.companyLicense'),
            dataIndex: 'companyLicense',
            width: 100,
        },
        {
            title: t('order.phoneNumber'),
            dataIndex: 'phoneNumber',
            width: 80,
        },
        {
            title: t('order.score'),
            dataIndex: 'score',
            width: 50,
        },
        {
            title: t('order.license'),
            dataIndex: 'license',
            width: 80,
        },
    ]);
    const columnsExcel = computed<TableColumnData[]>(() => [
        {
            title: t('order.consumeId'),
            key: 'consumeId',
        },
        {
            title: t('order.stationName'),
            key: 'stationName',
        },
        {
            title: t('order.customerName'),
            key: 'customerName',
        },
        {
            title: t('order.companyName'),
            key: 'companyName',
        },
        {
            title: t('order.companyLicense'),
            key: 'companyLicense',
        },
        {
            title: t('order.phoneNumber'),
            key: 'phoneNumber',
        },
        {
            title: t('order.score'),
            key: 'score',
        },
        {
            title: t('order.license'),
            key: 'license',
        },
        {
            title: t('order.fuelName'),
            key: 'fuelName',
        },
        {
            title: t('order.nzn'),
            key: 'nzn',
        },
        {
            title: t('order.price'),
            key: 'price',
        },
        {
            title: t('order.volume'),
            key: 'volume',
        },
        {
            title: t('order.amount'),
            key: 'amount',
        },
        {
            title: t('order.payAmount'),
            key: 'payAmount',
        },

        {
            title: t('order.status'),
            key: 'status',
            render({ record }) {
                return (
                    {
                        1: t('order.wzf'),
                        2: t('order.yzf'),
                    } as any
                )[record.status];
            },
        },
        {
            title: t('order.tradeTime'),
            key: 'tradeTime',
        },
    ]);

    const fetchData = async (params: any) => {
        console.log('params', params);
        setLoading(true);
        try {
            const data = await getList(params);
            renderData.value = data.result.records || [];
            pagination.current = params.current;
            pagination.total = data.result.total;
        } finally {
            setLoading(false);
        }
    };

    const changeStationAll = () => {
        if (isAllStation.value === true) {
            console.log(isAllStation.value);
        } else {
            console.log(isAllStation.value);
        }
    };

    const search = (pageNum?: number) => {
        if (formModel.value.time) {
            formModel.value.beginTime = formModel.value.time
                ? formModel.value.time[0]
                : '';
            formModel.value.endTime = formModel.value.time
                ? formModel.value.time[1]
                : '';
        }
        console.log('formModel.time.value', pagination);
        //    delete formModel.value.time;
        fetchData({
            ...formModel.value,
            current: pageNum || pagination.current,
            size: pagination.pageSize,
        });
    };

    const exportExcel = async (pageNum?: number) => {
        setLoading(true);
        if (formModel.value.time) {
            formModel.value.beginTime = formModel.value.time
                ? formModel.value.time[0]
                : '';
            formModel.value.endTime = formModel.value.time
                ? formModel.value.time[1]
                : '';
        }
        console.log('formModel.time.value', pagination);
        //    delete formModel.value.time;

        //   获取total
        const data = await getList({
            ...formModel.value,
            current: pageNum || pagination.current,
            size: pagination.pageSize,
        });
        //   根据total,查询所有的数据
        console.log(data.result.total);
        const dataEnd = await getList({
            ...formModel.value,
            current: 1,
            size: data.result.total,
        });
        renderExcelData.value = dataEnd.result.records || [];

        renderExcelData.value.forEach((item) => {
            if (item.staus == 1) {
                item.status = t('order.wzf');
            } else {
                item.status = t('order.yzf');
            }
        });

        setLoading(false);
        qee(
            columnsExcel.value,
            renderExcelData.value,
            `${'订单报表'}${formModel.value.time[0].valueOf()}${'--'}${formModel.value.time[1].valueOf()}`
        );
    };

    const onPageChange = (pageNum: number) => {
        pagination.current = pageNum;

        fetchData({
            ...formModel.value,
            size: pagination.pageSize,
            current: pageNum,
        });
    };
    search(1);

    const reset = () => {
        formModel.value = generateFormModel();
        console.log(formModel.value);
    };

    async function deleteMenuInfo(data: any) {
        await del({ id: data.id });
        search(1);
    }

    const handleChange = (
        checked: boolean | (string | boolean | number)[],
        column: Column,
        index: number
    ) => {
        if (!checked) {
            cloneColumns.value = showColumns.value
                .filter((item) => item.checked)
                .filter((item) => item.dataIndex !== column.dataIndex);
        } else {
            cloneColumns.value.splice(index, 0, column);
        }
    };

    const exchangeArray = <T extends Array<any>>(
        array: T,
        beforeIdx: number,
        newIdx: number,
        isDeep = false
    ): T => {
        const newArray = isDeep ? cloneDeep(array) : array;
        if (beforeIdx > -1 && newIdx > -1) {
            // 先替换后面的，然后拿到替换的结果替换前面的
            newArray.splice(
                beforeIdx,
                1,
                newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
            );
        }
        return newArray;
    };

    const popupVisibleChange = (val: boolean) => {
        if (val) {
            nextTick(() => {
                const el = document.getElementById(
                    'tableSetting'
                ) as HTMLElement;
                const sortable = new Sortable(el, {
                    onEnd(e: any) {
                        const { oldIndex, newIndex } = e;
                        exchangeArray(cloneColumns.value, oldIndex, newIndex);
                        exchangeArray(showColumns.value, oldIndex, newIndex);
                    },
                });
            });
        }
    };

    watch(
        () => columns.value,
        (val) => {
            cloneColumns.value = cloneDeep(val);
            cloneColumns.value.forEach((item, index) => {
                item.checked = true;
            });
            showColumns.value = cloneDeep(cloneColumns.value);
        },
        { deep: true, immediate: true }
    );
</script>

<style scoped lang="less">
    .container {
        padding: 0 20px 20px;
    }

    :deep(.arco-table-th) {
        &:last-child {
            .arco-table-th-item-title {
                margin-left: 16px;
            }
        }
    }

    .action-icon {
        margin-left: 12px;
        cursor: pointer;
    }

    .active {
        color: #0960bd;
        background-color: #e3f4fc;
    }

    .setting {
        display: flex;
        align-items: center;
        width: 200px;

        .title {
            margin-left: 12px;
            cursor: pointer;
        }
    }
</style>

<style lang="less">
    .arco-dropdown-open .arco-icon-down {
        transform: rotate(180deg);
    }
</style>
